# stories/views.py
# 功能：处理所有页面请求和AJAX交互

import requests
import re
from django.shortcuts import get_object_or_404
from django.contrib.auth import login, authenticate, logout
from django.http import JsonResponse
from django.db.models import Avg, Max
from django.db import IntegrityError  # 新增：用于捕获数据库唯一性冲突
from django.conf import settings
from .forms import CustomUserCreationForm, CustomUserChangeForm, StoryForm, CommentForm, RatingForm, StoryReviewForm
from .models import CustomUser, StoryCategory, Rating, SensitiveWord
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db.models import Count, Q  # 用于高效聚合查询
from django.utils import timezone

from .forms import CustomUserChangeForm
from .models import Story, Comment  # 确保导入相关模型


def home(request):
    """ 首页视图：展示分类和每个分类下的最新故事"""
    categories = StoryCategory.objects.all()
    
    # 获取每个分类下综合热度最高的故事（有封面图片的）
    featured_stories = []
    for category in categories:
        # 获取该分类下已发布的故事，按综合热度排序（评论数、评分、浏览量）
        top_story = Story.objects.filter(
            category=category, 
            status='published'
        ).annotate(
            comment_count=Count('comments')
        ).order_by('-comment_count', '-average_rating', '-view_count').first()
        
        # 只添加有封面图片或内容的故事
        if top_story and (top_story.cover_image or top_story.content):
            featured_stories.append(top_story)
    
    # 获取所有已发布的故事，按创建时间倒序排列
    all_stories = Story.objects.filter(status='published').order_by('-created_at')
    
    # 分页设置 - 每页显示8个故事（两行，每行4个）
    from django.core.paginator import Paginator
    paginator = Paginator(all_stories, 8)  # 每页显示8个故事
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    # 每个分类下的故事（用于Tab切换）- 每个分类显示8个故事
    stories_by_category = {}
    for category in categories:
        stories = Story.objects.filter(category=category, status='published').order_by('-created_at')[:8]
        stories_by_category[category.name] = stories

    context = {
        'categories': categories,
        'featured_stories': featured_stories,
        'stories_by_category': stories_by_category,
        'page_obj': page_obj,  # 添加分页对象
        'all_stories': page_obj,  # 为了向后兼容
    }
    return render(request, 'stories/home.html', context)


def register(request):
    """ 注册视图（ 已加固：表单校验 + 数据库异常捕获）"""
    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            try:
                # 尝试保存用户（表单已校验唯一性，但并发时仍可能冲突）
                user = form.save()
                username = form.cleaned_data.get('username')
                messages.success(request, f'账号 {username} 创建成功！请登录您的账户。')
                return redirect('stories:login')
            except IntegrityError:
                #  极端情况：并发注册导致唯一性冲突（虽然概率极低）
                messages.error(request, '用户名已被占用，请选择其他用户名')
                # 重新渲染页面，保留用户输入
                return render(request, 'stories/register.html', {'form': form})
    else:
        form = CustomUserCreationForm()

    return render(request, 'stories/register.html', {'form': form})


def user_login(request):
    """ 登录视图：支持用户名或邮箱登录"""
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        # 第一步：尝试用用户名登录
        user = authenticate(request, username=username, password=password)
        if user is None:
            # 第二步：尝试用邮箱登录
            try:
                user_obj = CustomUser.objects.get(email=username)
                user = authenticate(request, username=user_obj.username, password=password)
            except CustomUser.DoesNotExist:
                user = None

        if user is not None:
            login(request, user)
            messages.success(request, '登录成功！')
            # 如果是管理员，跳转到审核页面
            if user.is_admin:
                return redirect('stories:admin_review')
            else:
                return redirect('stories:home')
        else:
            messages.error(request, '用户名/邮箱或密码错误')

    return render(request, 'stories/login.html')


def user_logout(request):
    """ 登出视图"""
    logout(request)
    messages.success(request, '已成功登出')
    return redirect('stories:home')


def check_user_type(request):
    """ AJAX检查用户类型 """
    username = request.GET.get('username', '').strip()
    
    if not username:
        return JsonResponse({'exists': False})
    
    try:
        # 先尝试按用户名查找
        user = CustomUser.objects.get(username=username)
    except CustomUser.DoesNotExist:
        try:
            # 再尝试按邮箱查找
            user = CustomUser.objects.get(email=username)
        except CustomUser.DoesNotExist:
            return JsonResponse({'exists': False})
    
    return JsonResponse({
        'exists': True,
        'is_admin': user.is_admin
    })


@login_required
def ai_story_generator(request):
    """ AI故事生成页面（实际是故事发布页面）"""
    # 管理员不能使用AI故事生成功能
    if request.user.is_admin:
        messages.error(request, '管理员不能使用AI故事生成功能')
        return redirect('stories:admin_review')
    
    if request.method == 'POST':
        # 检查是否是AI生成请求
        if request.POST.get('action') == 'generate':
            # AI生成故事内容
            title = request.POST.get('title', '').strip()
            detailed_description = request.POST.get('detailed_description', '').strip()
            category_id = request.POST.get('category')
            word_limit = request.POST.get('word_limit', '500')  # 获取字数限制，默认500字
            story_type = request.POST.get('story_type', '故事')
            
            if not title:
                messages.error(request, '请输入故事标题')
                form = StoryForm()
                categories = StoryCategory.objects.all()
                return render(request, 'stories/ai_story_generator.html', {
                    'form': form,
                    'categories': categories,
                    'ai_generation_error': '请输入故事标题'
                })
            
            # 构造AI提示词，包含字数限制和详细描述
            category_name = ''
            if category_id:
                try:
                    category = StoryCategory.objects.get(id=category_id)
                    category_name = category.name
                except StoryCategory.DoesNotExist:
                    pass
            
            # 构建更精确的提示词
            prompt_parts = [f"请创作一个关于'{title}'的{category_name}{story_type}"]
            
            if detailed_description:
                prompt_parts.append(f"详细描述：{detailed_description}")
            
            prompt_parts.append(f"要求内容丰富、情节有趣，字数严格控制在{word_limit}字左右。")
            prompt = "，".join(prompt_parts)
            
            # 调用AI API，传递字数限制参数
            content, error = call_aliyun_ai_api(prompt, word_limit=word_limit)
            
            if content:
                # 返回AI生成的内容
                return JsonResponse({
                    'success': True,
                    'content': content
                })
            else:
                # 返回错误信息
                return JsonResponse({
                    'success': False,
                    'error': error or 'AI生成失败'
                })
        else:
            # 保存故事
            form = StoryForm(request.POST, request.FILES)
            if form.is_valid():
                story = form.save(commit=False)
                story.author = request.user

                # 可选：如果没有上传封面，可以后续用AI生成（这里留空）
                if not story.cover_image:
                    pass  # 未来可集成AI封面生成功能

                # 保存故事，状态默认为草稿
                story.save()

                # 如果用户点击了提交审核按钮
                if 'submit_for_review' in request.POST:
                    story.status = 'pending'
                    story.save()
                    messages.success(request, '故事已提交审核，等待管理员审核通过后即可发布！')
                else:
                    messages.success(request, '故事已保存为草稿！')
                    
                return redirect('stories:my_stories')
    else:
        form = StoryForm()

    categories = StoryCategory.objects.all()
    return render(request, 'stories/ai_story_generator.html', {
        'form': form,
        'categories': categories
    })


def story_detail(request, story_id):
    """ 故事详情页：展示故事内容、评论、评分等"""
    # 允许作者预览自己的草稿、待审核或被驳回的故事
    if request.user.is_authenticated:
        story = get_object_or_404(Story, id=story_id)
        # 如果故事未发布，检查是否是作者自己
        if story.status != 'published':
            if story.author != request.user:
                # 非作者无法查看未发布的故事
                story = get_object_or_404(Story, id=story_id, status='published')
    else:
        # 未登录用户只能查看已发布的故事
        story = get_object_or_404(Story, id=story_id, status='published')
    
    # 增加浏览量（避免重复刷新增加）
    if not request.session.get(f'viewed_story_{story_id}'):
        story.view_count += 1
        story.save(update_fields=['view_count'])
        request.session[f'viewed_story_{story_id}'] = True
    
    # 获取评论（包括回复）
    comments = story.comments.filter(parent=None).order_by('-created_at')
    
    # 获取用户评分（如果已登录且已评分）
    user_rating = None
    if request.user.is_authenticated:
        try:
            user_rating = Rating.objects.get(story=story, user=request.user)
        except Rating.DoesNotExist:
            pass
    
    context = {
        'story': story,
        'comments': comments,
        'user_rating': user_rating,
    }
    return render(request, 'stories/story_detail.html', context)


@login_required
def edit_story(request, story_id):
    """ 编辑故事：只有作者可以编辑"""
    story = get_object_or_404(Story, id=story_id)

    # 管理员不能编辑故事
    if request.user.is_admin:
        messages.error(request, '管理员不能编辑故事')
        return redirect('stories:admin_review')

    if story.author != request.user:
        messages.error(request, '您没有权限编辑此故事')
        return redirect('stories:story_detail', story_id=story.id)

    if request.method == 'POST':
        form = StoryForm(request.POST, request.FILES, instance=story)
        if form.is_valid():
            story = form.save()
            
            # 如果用户点击了提交审核按钮
            if 'submit_for_review' in request.POST:
                story.status = 'pending'
                story.save()
                messages.success(request, '故事已提交审核，等待管理员审核通过后即可发布！')
            else:
                messages.success(request, '故事已保存为草稿！')
                
            return redirect('stories:my_stories')
    else:
        form = StoryForm(instance=story)

    categories = StoryCategory.objects.all()
    return render(request, 'stories/edit_story.html', {
        'form': form,
        'story': story,
        'categories': categories
    })


@login_required
def my_stories(request):
    """ 个人创作中心：展示用户所有故事"""
    # 管理员不能查看个人创作中心
    if request.user.is_admin:
        messages.error(request, '管理员不能访问个人创作中心')
        return redirect('stories:admin_review')
        
    stories = Story.objects.filter(author=request.user).order_by('-created_at')
    return render(request, 'stories/my_stories.html', {'stories': stories})


@login_required
def story_library(request):
    """ 故事库：按分类和排序浏览所有已发布故事"""
    category_id = request.GET.get('category')
    sort_by = request.GET.get('sort', 'newest')  # 默认最新
    search_query = request.GET.get('q', '')  # 搜索查询词
    page = request.GET.get('page', 1)  # 当前页码

    # 基础查询
    stories = Story.objects.filter(status='published')

    # 应用搜索过滤
    if search_query:
        stories = stories.filter(
            Q(title__icontains=search_query) | Q(content__icontains=search_query)
        )

    # 应用分类过滤
    if category_id:
        stories = stories.filter(category_id=category_id)

    # 应用排序
    if sort_by == 'rating':
        stories = stories.order_by('-average_rating', '-rating_count')
    elif sort_by == 'views':
        stories = stories.order_by('-view_count')
    else:  # newest
        stories = stories.order_by('-created_at')

    # 分页设置
    from django.core.paginator import Paginator
    paginator = Paginator(stories, 4)  # 每页显示多少个故事卡片
    page_obj = paginator.get_page(page)

    categories = StoryCategory.objects.all()
    current_category = StoryCategory.objects.get(id=category_id) if category_id else None

    context = {
        'stories': page_obj,  # 使用分页对象
        'categories': categories,
        'current_category': current_category,
        'sort_by': sort_by,
        'search_query': search_query,  # 传递搜索查询词
    }
    return render(request, 'stories/story_library.html', context)


@login_required
def leaderboard(request):
    """ 排行榜视图：展示按评论数、评分、浏览量和综合排序的前十名故事 """
    # 获取所有已发布的故事
    published_stories = Story.objects.filter(status='published')
    
    # 按评论数排序（评论数多的在前）
    top_by_comments = published_stories.annotate(
        comment_count=Count('comments')
    ).order_by('-comment_count')[:10]
    
    # 按评分排序（平均评分高的在前）
    top_by_rating = published_stories.order_by('-average_rating', '-rating_count')[:10]
    
    # 按浏览量排序（浏览量多的在前）
    top_by_views = published_stories.order_by('-view_count')[:10]
    
    # 综合排序（评论数、评分、浏览量各占三分之一权重）
    # 为了计算综合得分，我们需要对各项数据进行归一化处理
    all_stories = list(published_stories.annotate(
        comment_count=Count('comments')
    ))
    
    if all_stories:
        # 获取各项数据的最大值用于归一化
        max_comments = max(story.comment_count for story in all_stories) or 1
        max_rating = max(story.average_rating for story in all_stories) or 1
        max_views = max(story.view_count for story in all_stories) or 1
        
        # 计算综合得分并排序
        stories_with_scores = []
        for story in all_stories:
            # 归一化各项数据
            normalized_comments = story.comment_count / max_comments if max_comments > 0 else 0
            normalized_rating = story.average_rating / max_rating if max_rating > 0 else 0
            normalized_views = story.view_count / max_views if max_views > 0 else 0
            
            # 计算综合得分（各占三分之一权重）
            composite_score = (normalized_comments + normalized_rating + normalized_views) / 3
            story.composite_score = composite_score
            stories_with_scores.append(story)
        
        # 按综合得分排序并取前十名
        top_by_composite = sorted(stories_with_scores, key=lambda x: x.composite_score, reverse=True)[:10]
    else:
        top_by_composite = []
    
    context = {
        'top_by_comments': top_by_comments,
        'top_by_rating': top_by_rating,
        'top_by_views': top_by_views,
        'top_by_composite': top_by_composite,
    }
    
    return render(request, 'stories/leaderboard.html', context)


@login_required
def admin_review(request):
    """ 管理员审核页面：只有管理员可以访问 """
    if not request.user.is_admin:
        messages.error(request, '您没有权限访问此页面')
        return redirect('stories:home')
    
    # 获取待审核的故事
    pending_stories = Story.objects.filter(status='pending').order_by('-created_at')
    
    # 手动词汇查询功能
    search_query = request.GET.get('search_query', '')
    search_results = []
    if search_query:
        # 在所有故事中搜索包含该词汇的内容
        search_results = Story.objects.filter(
            Q(title__icontains=search_query) | Q(content__icontains=search_query)
        ).order_by('-created_at')
    
    context = {
        'pending_stories': pending_stories,
        'search_query': search_query,
        'search_results': search_results,
    }
    return render(request, 'stories/admin_review.html', context)


@login_required
def review_story(request, story_id):
    """ 审核故事详情页面 """
    if not request.user.is_admin:
        messages.error(request, '您没有权限访问此页面')
        return redirect('stories:home')
    
    story = get_object_or_404(Story, id=story_id)
    
    # 只有待审核的故事才能被审核
    if story.status != 'pending':
        messages.error(request, '该故事不在待审核状态')
        return redirect('stories:admin_review')
    
    # 检测敏感词
    sensitive_words = SensitiveWord.objects.filter(is_active=True)
    detected_words = []
    
    for word_obj in sensitive_words:
        word = word_obj.word
        # 在标题和内容中查找敏感词
        if re.search(word, story.title, re.IGNORECASE) or re.search(word, story.content, re.IGNORECASE):
            detected_words.append(word)
    
    # 获取搜索查询词（如果有的话）
    search_query = request.GET.get('search_query', '')
    
    if request.method == 'POST':
        form = StoryReviewForm(request.POST, instance=story)
        if form.is_valid():
            story = form.save(commit=False)
            story.reviewed_at = timezone.now()
            story.reviewed_by = request.user
            
            if story.status == 'published':
                messages.success(request, f'故事《{story.title}》已审核通过并发布')
            elif story.status == 'rejected':
                messages.success(request, f'故事《{story.title}》已被驳回')
                
            story.save()
            return redirect('stories:admin_review')
    else:
        form = StoryReviewForm(instance=story)
    
    context = {
        'story': story,
        'form': form,
        'detected_words': detected_words,
        'search_query': search_query,
    }
    return render(request, 'stories/review_story.html', context)


@login_required
def admin_dashboard(request):
    """ 管理员数据统计页面 """
    if not request.user.is_admin:
        messages.error(request, '您没有权限访问此页面')
        return redirect('stories:home')
    
    # 统计数据
    total_stories = Story.objects.count()
    published_stories = Story.objects.filter(status='published').count()
    pending_stories = Story.objects.filter(status='pending').count()
    draft_stories = Story.objects.filter(status='draft').count()
    rejected_stories = Story.objects.filter(status='rejected').count()
    
    total_users = CustomUser.objects.count()
    total_comments = Comment.objects.count()
    total_ratings = Rating.objects.count()
    
    # 最近的故事
    recent_stories = Story.objects.order_by('-created_at')[:10]
    
    context = {
        'total_stories': total_stories,
        'published_stories': published_stories,
        'pending_stories': pending_stories,
        'draft_stories': draft_stories,
        'rejected_stories': rejected_stories,
        'total_users': total_users,
        'total_comments': total_comments,
        'total_ratings': total_ratings,
        'recent_stories': recent_stories,
    }
    return render(request, 'stories/admin_dashboard.html', context)


@login_required  # 必须登录才能访问
def profile(request):
    """
    个人资料页：
        - 显示用户基本信息 + 头像
        - 支持修改用户名、邮箱、手机号、简介、头像
        - 显示统计数据：已发布故事数、草稿故事数、评论数
    """

    # =============================
    #  第一部分：处理表单提交（修改资料）
    # ==============================
    if request.method == 'POST':
        # 检查是否是头像上传
        if 'avatar' in request.FILES:
            # 处理头像上传
            user = request.user
            user.avatar = request.FILES['avatar']
            user.save()
            messages.success(request, ' 头像更新成功！')
            return redirect('stories:profile')
        else:
            # 处理用户资料更新
            form = CustomUserChangeForm(request.POST, request.FILES, instance=request.user)
            if form.is_valid():
                form.save()  # 保存到数据库
                messages.success(request, ' 个人信息更新成功！')  # 显示成功提示
                return redirect('stories:profile')  # 刷新页面，显示最新数据
            # 如果表单无效，继续显示表单和错误
    else:
        # GET 请求：显示当前用户的资料表单
        form = CustomUserChangeForm(instance=request.user)

    # ==============================
    #  第二部分：计算用户统计数据（故事 + 评论）
    # ==============================
    # 查询当前用户的故事，按状态分类统计（一次数据库查询，高效！）
    story_stats = request.user.story_set.aggregate(
        published_count=Count('id', filter=Q(status='published')),  # 已发布故事数
        draft_count=Count('id', filter=Q(status='draft')),  # 草稿故事数
        pending_count=Count('id', filter=Q(status='pending')),  # 待审核故事数
        rejected_count=Count('id', filter=Q(status='rejected')),  # 已驳回故事数
        total_count=Count('id')  # 总故事数
    )

    # 查询当前用户的评论总数
    comment_count = request.user.comment_set.count()
    
    # 如果是管理员，获取审核相关的统计数据
    review_stats = None
    if request.user.is_admin:
        review_stats = {
            'total_pending': Story.objects.filter(status='pending').count(),
            'total_reviewed': Story.objects.filter(reviewed_by=request.user).count(),
            'total_published': Story.objects.filter(reviewed_by=request.user, status='published').count(),
            'total_rejected': Story.objects.filter(reviewed_by=request.user, status='rejected').count(),
        }

    # ==============================
    #  第三部分：准备模板上下文数据
    # ==============================
    context = {
        'form': form,  # 用户资料表单
        'published_story_count': story_stats['published_count'],  # 已发布故事数
        'draft_story_count': story_stats['draft_count'],  # 草稿故事数
        'pending_story_count': story_stats['pending_count'],  # 待审核故事数
        'rejected_story_count': story_stats['rejected_count'],  # 已驳回故事数
        'total_story_count': story_stats['total_count'],  # 总故事数（可选显示）
        'comment_count': comment_count,  # 评论总数
        'review_stats': review_stats,  # 管理员审核统计数据
    }

    # 渲染模板
    return render(request, 'stories/profile.html', context)


@login_required
def change_password(request):
    """ 修改密码"""
    if request.method == 'POST':
        old_password = request.POST.get('old_password')
        new_password1 = request.POST.get('new_password1')
        new_password2 = request.POST.get('new_password2')

        if not request.user.check_password(old_password):
            messages.error(request, '原密码错误')
        elif new_password1 != new_password2:
            messages.error(request, '两次新密码不一致')
        else:
            request.user.set_password(new_password1)
            request.user.save()
            messages.success(request, '密码修改成功，请重新登录')
            return redirect('stories:login')

    return render(request, 'stories/change_password.html')


# =============== AJAX 视图 ===============

@login_required
def add_comment(request, story_id):
    """ AJAX添加评论"""
    if request.method == 'POST':
        story = get_object_or_404(Story, id=story_id)
        content = request.POST.get('content', '').strip()
        parent_id = request.POST.get('parent_id')

        if not content:
            return JsonResponse({'error': '评论内容不能为空'}, status=400)

        comment = Comment(story=story, author=request.user, content=content)
        if parent_id:
            try:
                parent_comment = Comment.objects.get(id=parent_id)
                comment.parent = parent_comment
            except Comment.DoesNotExist:
                pass  # 如果父评论不存在，就当普通评论处理

        comment.save()

        return JsonResponse({
            'success': True,
            'comment': {
                'id': comment.id,
                'author': comment.author.username,
                'avatar': comment.author.avatar.url if comment.author.avatar else '',
                'content': comment.content,
                'created_at': comment.created_at.strftime('%Y-%m-%d %H:%M'),
                'is_author': True,  # 因为是当前用户发的
            }
        })

    return JsonResponse({'error': '请求方法错误'}, status=400)


@login_required
def delete_comment(request, comment_id):
    """ AJAX删除评论（作者或故事作者可删）"""
    if request.method == 'POST':
        comment = get_object_or_404(Comment, id=comment_id)

        if comment.author == request.user or comment.story.author == request.user:
            comment.delete()
            return JsonResponse({'success': True})
        else:
            return JsonResponse({'error': '您没有权限删除此评论'}, status=403)

    return JsonResponse({'error': '请求方法错误'}, status=400)


@login_required
def rate_story(request, story_id):
    """ AJAX评分（1-5星）"""
    if request.method == 'POST':
        story = get_object_or_404(Story, id=story_id)
        score = request.POST.get('score')

        # 检查用户是否是故事作者
        if story.author == request.user:
            return JsonResponse({'error': '您不能给自己的文章评分'}, status=400)

        try:
            score = int(score)
            if score < 1 or score > 5:
                return JsonResponse({'error': '评分必须在1-5之间'}, status=400)
        except ValueError:
            return JsonResponse({'error': '无效的评分值'}, status=400)

        # 创建或更新评分
        rating, created = Rating.objects.update_or_create(
            story=story,
            user=request.user,
            defaults={'score': score}
        )

        # 重新计算平均分和评分人数
        ratings = Rating.objects.filter(story=story)
        avg_rating = ratings.aggregate(Avg('score'))['score__avg'] or 0
        rating_count = ratings.count()

        story.average_rating = round(avg_rating, 2)
        story.rating_count = rating_count
        story.save()

        return JsonResponse({
            'success': True,
            'average_rating': story.average_rating,
            'rating_count': story.rating_count,
        })

    return JsonResponse({'error': '请求方法错误'}, status=400)


def search_stories(request):
    """ AJAX搜索故事（按标题和内容模糊匹配）"""
    if request.method == 'GET':
        query = request.GET.get('q', '')
        page = int(request.GET.get('page', 1))
        per_page = 12  # 每页显示12个故事
        
        if query:
            stories = Story.objects.filter(
                status='published'
            ).filter(
                Q(title__icontains=query) | Q(content__icontains=query)
            ).order_by('-created_at')
            
            # 计算分页信息
            total_stories = stories.count()
            total_pages = (total_stories + per_page - 1) // per_page
            
            # 分页
            start_index = (page - 1) * per_page
            end_index = start_index + per_page
            stories = stories[start_index:end_index]

            results = [{
                'id': story.id,
                'title': story.title,
                'author': story.author.username,
                'category': story.category.name,
                'created_at': story.created_at.strftime('%Y-%m-%d'),
                'content': story.content,
                'view_count': story.view_count,
                'average_rating': story.average_rating,
                'rating_count': story.rating_count,
            } for story in stories]

            return JsonResponse({
                'results': results,
                'total_pages': total_pages,
                'current_page': page,
                'total_stories': total_stories
            })

    return JsonResponse({
        'results': [],
        'total_pages': 0,
        'current_page': 1,
        'total_stories': 0
    })


def call_aliyun_ai_api(prompt, word_limit=None):
    """
    调用阿里云AI API生成故事内容
    """
    try:
        # 尝试导入dashscope库
        try:
            import dashscope
        except ImportError as e:
            return None, f"无法导入dashscope库: {str(e)}"
        
        # 从Django设置中获取API密钥
        from django.conf import settings
        api_key = getattr(settings, 'DASHSCOPE_API_KEY', None)
        if not api_key:
            return None, "未配置阿里云API密钥，请在settings.py中设置DASHSCOPE_API_KEY"
        
        # 设置API密钥
        dashscope.api_key = api_key
        
        # 构建提示词，包含字数限制
        if word_limit:
            full_prompt = f"{prompt}，请严格控制在{word_limit}字左右。"
        else:
            full_prompt = prompt
            
        # 调用阿里云通义千问API
        try:
            response = dashscope.Generation.call(
                model='qwen-plus',
                prompt=full_prompt,
                max_tokens=int(word_limit) if word_limit else 1000,
                temperature=0.8,
                top_p=0.9
            )
        except Exception as e:
            return None, f"调用阿里云API时发生错误: {str(e)}"
        
        # 检查响应
        if hasattr(response, 'status_code') and response.status_code == 200:
            if hasattr(response, 'output') and hasattr(response.output, 'text'):
                content = response.output.text
                if content:
                    return content, None
                else:
                    return None, "API返回内容为空"
            else:
                return None, "API响应格式不正确"
        else:
            # 获取错误信息
            error_message = "未知错误"
            if hasattr(response, 'message'):
                error_message = response.message
            elif hasattr(response, 'error'):
                error_message = response.error
            return None, f"API调用失败: {error_message}"
            
    except Exception as e:
        return None, f"发生未预期的错误: {str(e)}"
